#include <pfring.h>
#include <sys/types.h>
#include <stdlib.h>

#include "common.h"
#include "change.h"

#define MAX_PACKET_SIZE 1500

int main(int argc, char *argv[])
{
    // 构造帧头部
    struct FRAME_HEADER frame_header;
    struct IP_HEADER ip_header;
    struct ICMP_ECHO icmp_echo;

    char dmac_char[18] = "f8:8c:21:26:cc:91 ";
    char smac_char[18] = "00:0c:29:f8:81:83";

    mac_char_to_u_char(dmac_char, &(frame_header.dmac));
    mac_char_to_u_char(smac_char, &(frame_header.smac));
    frame_header.type = 0x0008;

    // 构造IP头部
    ip_header.sour_ip.s_addr = inet_addr("192.168.66.101");
    ip_header.dest_ip.s_addr = inet_addr("192.168.6.1");
    ip_header.vension_and_header = 0x45;
    ip_header.type_of_service = 0x00;
    // ip_header.lenght_of_packet=htons(sizeof(ip_header)+sizeof(icmp_echo));
    ip_header.lenght_of_packet = 0x2e00;
    ip_header.id = 0xdc07;
    ip_header.flags_and_slice_info = 0x0000;
    ip_header.ttl = 0x40;
    ip_header.type_of_protocol = 0x01;
    ip_header.checksum = htons(calculate_checksum((u_int16_t *)&ip_header, sizeof(ip_header)));
    // return 0;

    // // 构造ICMP 头部
    icmp_echo.type = 0x8;
    icmp_echo.code = 0x0;
    icmp_echo.seq = 0x01;
    icmp_echo.ident = 0x00;
    icmp_echo.checksum = 0x00;
    gettimeofday(&(icmp_echo.tv), NULL);
    icmp_echo.checksum = htons(calculate_checksum((u_int16_t *)&icmp_echo, sizeof(icmp_echo)));

    int lenght_of_packet = sizeof(frame_header) + sizeof(ip_header) + sizeof(icmp_echo);
    u_char buf[MAX_PACKET_SIZE];
    u_char buffer[MAX_PACKET_SIZE];

    memcpy(buf, &frame_header, sizeof(frame_header));
    memcpy(buf + sizeof(frame_header), &ip_header, sizeof(ip_header));
    memcpy(buf + sizeof(frame_header) + sizeof(ip_header), &icmp_echo, sizeof(icmp_echo));

    char *device_name = "ens33";
    u_int32_t flags = 265;
    pfring *ring = pfring_open(device_name, DEFAULT_SNAPLEN, flags);
    if (ring == NULL)
        return -1;

    if (pfring_enable_ring(ring) != 0)
    {
        printf("Unable to enable ring :-(\n");
        pfring_close(ring);
        return (-1);
    }

    pfring_send(ring, (char *)buf, 60, 1);

    for (int i = 0; i < lenght_of_packet; i++)
    {
        printf("%x ", *(buf + i));
        if (i == 13)
            printf("\n");
        if (i > 14 && (i - 14) % 4 == 3)
            printf("\n");
    }
    printf("send\n");
}